package me.gavin.util

import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import me.gavin.base.Gavin
import java.io.File
import java.io.FileWriter
import java.io.PrintWriter

/**
 * 全局异常捕获工具
 *
 * @author gavin.xiong 2018/3/29
 */
object CrashHandler : Thread.UncaughtExceptionHandler {

    private var defaultHandler: Thread.UncaughtExceptionHandler? = null

    fun init() {
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(this)
    }

    override fun uncaughtException(t: Thread, e: Throwable) {
        printException2SDCard(e)
        defaultHandler?.uncaughtException(t, e)
        // TODO: 2018/3/29  上传异常信息到服务器 & 延时杀死进程
        // SystemClock.sleep(2000);
        // Process.killProcess(Process.myPid())
        // System.exit(1)
    }

    private fun printException2SDCard(e: Throwable) {
        val parent = getLogDir(Gavin.app)
        if (parent.isNullOrBlank()) return

        val time = System.currentTimeMillis()
        val path = "%1\$s/CRASH_%2\$tY.%2\$tm.%2\$td_%2\$tH.%2\$tM.%2\$tS.trace".format(parent, time)
        try {
            PrintWriter(FileWriter(File(path))).use {
                val info = Gavin.app.packageManager.getPackageInfo(Gavin.app.packageName, PackageManager.GET_ACTIVITIES)
                it.println("异常时间：%1\$tF %1\$tT".format(time))
                it.println("应用版本：" + info.versionName)
                it.println("应用版本号：" + info.versionCode)
                it.println("Android版本：" + Build.VERSION.RELEASE)
                it.println("Android版本号：" + Build.VERSION.SDK_INT)
                it.println("手机制造商：" + Build.MANUFACTURER)
                it.println("手机型号：" + Build.MODEL)
                e.printStackTrace(it)
                var cause = e.cause
                while (cause != null) {
                    cause.printStackTrace(it)
                    cause = cause.cause
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 获取日志文件夹 - /storage/sdcard0/Android/data/com.example.dir/files/log
     */
    private fun getLogDir(context: Context): String? {
        return if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() && context.getExternalFilesDir("log") != null) {
            context.getExternalFilesDir("log")!!.path
        } else {
            null
        }
    }
}